package com.skcc.cop.mrtaxi.control;

import java.util.ArrayList;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.skcc.cop.mrtaxi.biz.destination.DestinationEntity;


/**
 * @author tmkim
 * 
 */
public class DataBaseControl {
	private DBHelper mDbHelp;

	public DataBaseControl(Context context) {
		mDbHelp = new DBHelper(context);
	}

	synchronized private SQLiteDatabase getReadableDatabase() {
		return mDbHelp.getReadableDatabase();
	}

	synchronized private SQLiteDatabase getWritableDatabase() {
		return mDbHelp.getWritableDatabase();
	}

	synchronized private void closeDatabase(SQLiteDatabase database) {
		database.close();
	}

	

	public class DBHelper extends SQLiteOpenHelper {

		public DBHelper(Context context) {
			super(context, "mr_taxi.db", null, 1);
		}

		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DestinationEntity.CREATE_TABLE);
			

		}

		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + DestinationEntity.TABLE_NAME);
			onCreate(db);
		}
	}
	
	
	public boolean insertDestination(DestinationEntity destinationEntity) {
		SQLiteDatabase database = getWritableDatabase();
		
		boolean reBool = destinationEntity.insertEntity(database, destinationEntity.getAddress1(), destinationEntity.getCity(), 
				destinationEntity.getDistrict(), 
				destinationEntity.getStreet(), destinationEntity.getPassenger(), destinationEntity.getLati(), 
				destinationEntity.getLongi(), destinationEntity.getAccuracy(), destinationEntity.getRegTime());
		closeDatabase(database);
		
		return reBool;
	}
	
	
	public boolean updateDestination(DestinationEntity destinationEntity) {
		SQLiteDatabase database = getWritableDatabase();

		boolean reBool = destinationEntity.updateEntity(database, destinationEntity.getId(), destinationEntity.getAddress1(),
				destinationEntity.getCity(), 
				destinationEntity.getDistrict(), destinationEntity.getStreet(), destinationEntity.getPassenger(), 
				destinationEntity.getLati(), destinationEntity.getLongi(), destinationEntity.getAccuracy());
		closeDatabase(database);
		
		return reBool;
	}
	
	public ArrayList<DestinationEntity> getDestinationListAll() {
		SQLiteDatabase database = getReadableDatabase();
		ArrayList<DestinationEntity> reList = new DestinationEntity().getEntity(database);

		closeDatabase(database);
		return reList;
	}
	
	public boolean deleteDestination(int id) {
		SQLiteDatabase database = getWritableDatabase();
		boolean reBool = new DestinationEntity().deleteEntity(database, id);
		closeDatabase(database);
		return reBool;
	}
	
	
	
	
	
}
